/*
 * @(#)UdbFilter.java
 *
 * Copyright (c)	2014-2020. All Rights Reserved.	GuangZhou hhmk Technology Company LTD.
 */
package com.swift.dts.service.core;

import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import com.swift.core.auth.Login;
import com.swift.core.filter.RequestFilter;
import com.swift.core.model.HttpServiceRequest;
import com.swift.core.model.ServiceRequest;
import com.swift.core.model.data.DataModel;
import com.swift.core.service.processor.ReqInterfaceFactory;
import com.swift.core.session.AbstractSession;
import com.swift.core.session.SessionCrypt;
import com.swift.exception.NoWarnException;
import com.swift.exception.ResultCode;


/**
 * 单点登录过滤器
 *
 * @author
 */
@Service
@Order(0)
public class UserFilter implements RequestFilter {

    private static final Logger log = LoggerFactory.getLogger(UserFilter.class);
    // cookie的生存期
    static final int MAX_AGE = 60 * 60 * 24;

    @Autowired
    private SessionCrypt sessionCrypt;

    @Override
    public void doFilter(ServiceRequest req) {
        updateSessionUser(req);
        Object obj = ReqInterfaceFactory.getInterfaceTrueObj(req.getMethod(), req.getInterfaceVersion());
        Login loginValidator = obj.getClass().getAnnotation(Login.class);
        if (loginValidator != null) {
            if (req.getSessionUser() == null ) {
                // || TypeUtil.isNull(req.getSessionUser().getLoginType())) { TODO
                throw new NoWarnException(ResultCode.NO_LOGIN, "您未登录系统");
            }
        }
    }

    public void updateSessionUser(ServiceRequest req) {
        try {
            AbstractSession sessionUser = null;
            Cookie sessionUserCookies = null;
            if(!(req instanceof HttpServiceRequest)) return;
            //先查看有没有cookies有的话直接设置对象
            HttpServletRequest servletRequest = ((HttpServiceRequest) req).getRequest();
            Cookie[] cookies = servletRequest.getCookies();
            if (cookies != null && cookies.length != 0) {
                for (int i = 0; i < cookies.length; i++) {
                    if (cookies[i].getName() != null && cookies[i].getName().equals(AbstractSession.SESSION_NAME)) {
                        sessionUserCookies = cookies[i];
                        sessionUser = (AbstractSession)sessionCrypt.decrypt(sessionUserCookies.getValue());
                    }
                }
            }

            //从cookie中获取不到sessionUser的话，从接口参数中再获取一次
            //小程序客户端无法使用cookie
            if (sessionUser == null) {
                DataModel paramSDM = req.getData();
                sessionUser = (AbstractSession)sessionCrypt.decrypt(paramSDM.getString(AbstractSession.SESSION_NAME));
            }
            if (sessionUser == null) {
                return;
            }
            req.setSessionUser(sessionUser);
            if (sessionUser.getSessionCreateTime() == null) {
                return;
            }
            Date sesionUntilTime = new Date(sessionUser.getSessionCreateTime().getTime() + MAX_AGE * 1000L - 60 * 10 * 1000L);
            //cookie过期前10分钟更新cookie
            if (sessionUserCookies != null && (new Date()).after(sesionUntilTime)) {
                HttpServletResponse servletResponse = ((HttpServiceRequest) req).getResponse();
                sessionUser.setSessionCreateTime(new Date());
                String cookieSeeionUser = sessionCrypt.encrypt(sessionUser);
                Cookie sessionCookie = new Cookie(AbstractSession.SESSION_NAME, cookieSeeionUser);
                sessionCookie.setPath(sessionUserCookies.getPath());
                sessionCookie.setSecure(sessionUserCookies.getSecure());
                if (sessionUserCookies.getDomain() != null) {
                    sessionCookie.setDomain(sessionUserCookies.getDomain());
                }
                sessionCookie.setHttpOnly(sessionUserCookies.isHttpOnly());
                sessionCookie.setMaxAge(MAX_AGE);
                servletResponse.addCookie(sessionCookie);
            }
        } catch (Exception ex) {
            log.error("解释登录信息错误:", ex);
        }
    }
}
